#include "player_spawn.h"

CPlayerSpawn::CPlayerSpawn(float fX, float fY, float fZ, ENTITY_ID nEntityId):
     CStaticEntity("player_spawn", ENT_PLAYER_SPAWN, fX, fY, fZ, false),
     m_nPlayerId(nEntityId),
     m_pPlayer(nullptr)
{
    /**
     * A player spawn entity. This entity controls the spawn position of an
     * entity, and is in control of dynamically creating / removing the player.
     *
     * @param float fX The X position of the entity
     * @param float fY The Y position of the entity
     * @param float fZ The Z position of the entity
     * @param ENTITY_ID nEntityId The ID of the player to spawn
     */
    setPermanent(true);
}

CPlayer *CPlayerSpawn::getPlayerToSpawn() const
{
    /**
     * @return CPlayer* A pointer to the player this spawner spawns.
     */
    return m_pPlayer;
}

ENTITY_ID CPlayerSpawn::getIdToSpawn() const
{
    /**
     * @return ENTITY_ID The ID of the player to spawn
     */
    return m_nPlayerId;
}

void CPlayerSpawn::onCreate(CMap *pMap)
{
    /**
     * Executes when an entity is created. Create the player that this spawner
     * should spawn.
     *
     * @param CMap The map the entity is being spawned on
     */
    if (getIdToSpawn() == ENT_PLAYER_1 ||
        getIdToSpawn() == ENT_PLAYER_2)
    {
        // We're only interested in the first 2 players for now.
        CPlayer *pPlayer(new CPlayer(getX(), getY(), getZ(), getIdToSpawn()));
        pPlayer->onCreate(pMap);

        CBomb *pBomb(new CBomb());
        pPlayer->addWeapon(pBomb);
        pBomb->setOwner(this);
        pPlayer->setActiveWeapon(pBomb);
        pPlayer->attachEntity(pBomb, 0.0f, 0.0f, 0.0f);
        pBomb->setPosition(pPlayer->getX(), pPlayer->getY() + 5.0f, 
            pPlayer->getZ());

        CEntityContainer::getInstance()->addEntity(pPlayer);
        m_pPlayer = pPlayer;


        m_pPlayer->setPermanent(true);
    }
}

void CPlayerSpawn::reset()
{
    /**
     * Executed when a map is reset. Reset the player's position and respawn
     * the player.
     */
    if (m_pPlayer != nullptr)
    {
        m_pPlayer->setVisible(true);
        m_pPlayer->reset();
        m_pPlayer->respawn();
        m_pPlayer->setPosition(getX(), getY(), getZ());
        m_pPlayer->onCreate(CMapContainer::getInstance()->getCurrentMap());
    }
}